package de.bmuskalla.brainfuck;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Brainfuck {
	private static String program;
	private static String filename;
	private static boolean enableDebugger;

	public static void main(String[] args) {
		// parse arguments
		for (int i = 0; i < args.length; i++) {
			String arg = args[i];
			if (arg.equals("-debug")) {
				// enable debugging
				enableDebugger = true;
			} else {
				// filename - run it
				filename = arg;
			}
		}
		readProgramFile();

		BFInterpreter interpreter = new BFInterpreter();
		interpreter.load(program);
		interpreter.addBreakpoint(4);

		if (enableDebugger) {
			final BFDebuggerListener debugListener = new BFDebuggerListener();
			debugListener.setInterpreter(interpreter);
			new Thread(debugListener).start();
		}
		interpreter.run(enableDebugger);
	}

	private static void readProgramFile() {
		File file = new File(filename);
		Scanner scanner = null;
		try {
			scanner = new Scanner(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		while (scanner.hasNextLine()) {
			program += scanner.nextLine() + "\n";
		}
	}
}
